<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
         //自定义MyPromise类
         class MyPromise {
            constructor(handle) {
                this['[[PromiseState]]'] = 'pendding';
                this['[[PromiseResult]]'] = undefined;
                handle(this.#_resolve.bind(this),this.#_reject.bind(this))
                this.resolveFn = undefined;  // 保存 onResolved 函数
                this.rejectFn = undefined; // 保存onRejected函数；
            }

            #_resolve(val) { // 私有方法 需要在前面加上#号，只能类的内部调用外部不能调用
                this['[[PromiseState]]'] = 'fulfilled';
                this['[[PromiseResult]]'] = val;

                setTimeout(()=>{
                    this.resolveFn(val);
                })
            }

            #_reject(val) {
                this['[[PromiseState]]'] = 'rejected';
                this['[[PromiseResult]]'] = err;
               
                setTimeout(()=>{
                    this.rejectFn(val);
                })

                setTimeout(()=>{
                    throw new Error(err);
                })
            }

            then(onResolved,onRejected){
                this.resolveFn = onResolved;
                this.rejectFn = onRejected;
            }

        }


        let p = new MyPromise((resolve, reject) => {
            // setTimeout(() => {
                resolve("success");
            // }, 1000);
        })

        p.then(res => {
            console.log("执行了onResolved",res);
        }, err => {

        });  // 调用 类里的then方法；

    </script>
</body>
</html>